using System.Diagnostics;
using System.Text;
using System.Text.Json;
using MassTransit;
using WeatherSystem.API.Configurations;

namespace WeatherSystem.API.Services.MessageQueue
{
    /// <summary>
    /// RabbitMQ消息队列服务实现
    /// </summary>
    public class RabbitMQService : IMessageQueueService
    {
        private readonly IPublishEndpoint _publishEndpoint;
        private readonly IBusinessMetricsService _metricsService;
        private readonly ILogger<RabbitMQService> _logger;

        public RabbitMQService(
            IPublishEndpoint publishEndpoint,
            IBusinessMetricsService metricsService,
            ILogger<RabbitMQService> logger)
        {
            _publishEndpoint = publishEndpoint;
            _metricsService = metricsService;
            _logger = logger;
        }

        public async Task PublishWeatherDataCollectionTask(WeatherDataCollectionTask task)
        {
            using var activity = _metricsService.StartActivity("publish_weather_collection_task");
            activity?.SetTag("task.id", task.TaskId);
            activity?.SetTag("task.city_count", task.CityIds.Length);
            activity?.SetTag("task.priority", task.Priority);

            try
            {
                await _publishEndpoint.Publish<WeatherDataCollectionTask>(task);
                
                _logger.LogInformation("天气数据采集任务已发布: {TaskId}, 城市数量: {CityCount}", 
                    task.TaskId, task.CityIds.Length);
                    
                activity?.SetStatus(ActivityStatusCode.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布天气数据采集任务失败: {TaskId}", task.TaskId);
                activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
                throw;
            }
        }

        public async Task PublishBatchDataProcessingTask(BatchDataProcessingTask task)
        {
            using var activity = _metricsService.StartActivity("publish_batch_processing_task");
            activity?.SetTag("task.id", task.TaskId);
            activity?.SetTag("task.operation_type", task.OperationType);
            activity?.SetTag("task.target_count", task.TargetIds.Length);

            try
            {
                await _publishEndpoint.Publish<BatchDataProcessingTask>(task);
                
                _logger.LogInformation("批量数据处理任务已发布: {TaskId}, 操作类型: {OperationType}, 目标数量: {TargetCount}", 
                    task.TaskId, task.OperationType, task.TargetIds.Length);
                    
                activity?.SetStatus(ActivityStatusCode.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布批量数据处理任务失败: {TaskId}", task.TaskId);
                activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
                throw;
            }
        }

        public async Task PublishDataExportTask(DataExportTask task)
        {
            using var activity = _metricsService.StartActivity("publish_data_export_task");
            activity?.SetTag("task.id", task.TaskId);
            activity?.SetTag("task.export_type", task.ExportType);
            activity?.SetTag("task.data_type", task.DataType);

            try
            {
                await _publishEndpoint.Publish<DataExportTask>(task);
                
                _logger.LogInformation("数据导出任务已发布: {TaskId}, 导出类型: {ExportType}, 数据类型: {DataType}", 
                    task.TaskId, task.ExportType, task.DataType);
                    
                activity?.SetStatus(ActivityStatusCode.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布数据导出任务失败: {TaskId}", task.TaskId);
                activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
                throw;
            }
        }

        public async Task PublishAlertNotification(AlertNotificationMessage notification)
        {
            using var activity = _metricsService.StartActivity("publish_alert_notification");
            activity?.SetTag("alert.id", notification.AlertId);
            activity?.SetTag("alert.type", notification.AlertType);
            activity?.SetTag("alert.severity", notification.Severity);

            try
            {
                await _publishEndpoint.Publish<AlertNotificationMessage>(notification);
                
                _logger.LogInformation("告警通知已发布: {AlertId}, 类型: {AlertType}, 严重程度: {Severity}", 
                    notification.AlertId, notification.AlertType, notification.Severity);
                    
                activity?.SetStatus(ActivityStatusCode.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布告警通知失败: {AlertId}", notification.AlertId);
                activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
                throw;
            }
        }

        public async Task PublishSystemEvent(SystemEventMessage eventMessage)
        {
            using var activity = _metricsService.StartActivity("publish_system_event");
            activity?.SetTag("event.id", eventMessage.EventId);
            activity?.SetTag("event.type", eventMessage.EventType);
            activity?.SetTag("event.source", eventMessage.Source);

            try
            {
                await _publishEndpoint.Publish<SystemEventMessage>(eventMessage);
                
                _logger.LogDebug("系统事件已发布: {EventId}, 类型: {EventType}, 来源: {Source}", 
                    eventMessage.EventId, eventMessage.EventType, eventMessage.Source);
                    
                activity?.SetStatus(ActivityStatusCode.Ok);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发布系统事件失败: {EventId}", eventMessage.EventId);
                activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
                throw;
            }
        }
    }
}